/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.meteocal.EJB.sessionBeans;

import it.polimi.meteocal.EJB.entities.User;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Marianna
 */
@Stateless
public class SearchManager {

    @PersistenceContext
    private EntityManager em;

    public List<String> search2(String search) {
        char searchArray[] = new char[search.length()];
        searchArray = search.toCharArray();
        int i = 0;
        while (!(i == search.length() || Character.isWhitespace(searchArray[i]))) {
            i++;
        }
        String word1 = null;
        String word2 = null;
        word1 = search.substring(0, i);

        if (i != search.length()) {
            int j = i + 1;
            while (!(j == search.length() || Character.isWhitespace(searchArray[j]))) {
                j++;
            }
            word2 = search.substring(i + 1, j);
        }
        
        Query q4 = em.createNativeQuery("SELECT DISTINCT username FROM User  WHERE (username ='" + word1 + "' OR username ='" + word2 + "') OR (name='" + word1 + "' OR name='" + word2 + "') OR (surname='" + word1 + "' OR surname='" + word2 + "')");
       // List<User> users = new ArrayList<User>(); 
        List<String> users = q4.getResultList();
        return users;
    }

}
